﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Net;
using Card.Security;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Text;
using Card.Common;

namespace Card.Web
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class CardService : IHttpHandler
    {
        private Card.Security.Passport m_Passport = null;

        public Card.Security.Passport Passport
        {
            get
            {
                if (m_Passport == null)
                {
                    m_Passport = Card.Security.CookieManager.GetPassport();
                }
                return m_Passport;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            string action = context.Request.QueryString["a"].ToUpper();
            switch (action)
            {
                case "SM"://保存名片
                    this.SaveMP(context);
                    break;
                case "AC":
                    this.AddCart(context);
                    break;
                case "GO"://得到最新订单信息
                    this.GetNewestOrder(context);
                    break;
                default:
                    break;
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        #region SaveMP
        /// <summary>
        /// 保存用户名片信息
        /// </summary>
        /// <param name="context"></param>
        private void SaveMP(HttpContext context)
        {
            string result = string.Empty;
            try
            {
                string[] cinfo = Card.Security.Utility.DecryptString(context.Request.Form["cinfo"]).Split('|');

                int cardID = 0;
                if (!string.IsNullOrEmpty(context.Request.Form["cid"]) && BAF.Utility.ValidationHelper.IsNumber(context.Request.Form["cid"]))
                {
                    cardID = int.Parse(context.Request.Form["cid"]);
                }

                Entity.UserCard card = new Card.Entity.UserCard();
                card.ID = cardID > 0 ? cardID : BAF.BLL.SYSSequenceManager.GetSequence(CONST.SEQUENCE_CODE.USER_CARD_ID, null);
                card.FrontImage = cinfo[0];
                card.BackImage = cinfo[1];
                card.TemplateID = int.Parse(cinfo[2]);
                card.TemplateName = cinfo[3];
                card.Style = cinfo[4];
                card.UserID = this.Passport.UserID;
                if (BLL.UserCardManager.Save(card, this.Passport))
                {
                    this.SaveMPFields(context, CONST.CARD_FACE_TYPE.FRONT, card.ID);
                    this.SaveMPFields(context, CONST.CARD_FACE_TYPE.BACK, card.ID);
                    this.SavaMPLogo(context, CONST.CARD_FACE_TYPE.FRONT, card.ID);
                    this.SavaMPLogo(context, CONST.CARD_FACE_TYPE.BACK, card.ID);
                    this.CreateMPFile(context, card.ID);
                }
                result = string.Format("{{'r':'y','cid':'{0}','msg':'success'}}", card.ID);
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex.ToString());
                result = string.Format("{{'r':'n','msg':'{0}'}}", ex.Message);
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write(result);
        }
        /// <summary>
        /// 保存用户名片字段信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="faceType"></param>
        /// <param name="cardID"></param>
        private void SaveMPFields(HttpContext context, string faceType, int cardID)
        {

            string[] arrFields = context.Request.Form["fields" + faceType].Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries);
            BLL.UserCardFieldManager.Delete(cardID, faceType, Passport);
            foreach (string fieldstr in arrFields)
            {
                string[] arrField = fieldstr.Split('|');

                Entity.UserCardField field = new Card.Entity.UserCardField();
                field.UserCardID = cardID;
                field.ImageType = faceType;
                field.Content = Card.Utility.TextUtility.JSUnescape(arrField[0]);
                field.Sort = int.Parse(arrField[1]);
                field.PosX = decimal.Parse(arrField[2]);
                field.PosY = decimal.Parse(arrField[3]);
                field.Direction = arrField[4];
                field.Color = Card.Utility.TextUtility.JSUnescape(arrField[5]);
                field.FontSize = decimal.Parse(arrField[6]);
                field.FontFamily = Card.Utility.TextUtility.JSUnescape(arrField[7]);
                field.FontStyle = arrField[8];

                BLL.UserCardFieldManager.Add(field, this.Passport);
            }
        }
        /// <summary>
        /// 保存用户名片Logo信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="faceType"></param>
        /// <param name="cardID"></param>
        private void SavaMPLogo(HttpContext context, string faceType, int cardID)
        {
            BLL.UserCardLogoManager.Delete(cardID, faceType, Passport);
            if (!string.IsNullOrEmpty(context.Request.Form["logo" + faceType]))
            {
                string[] arr = context.Request.Form["logo" + faceType].Split('|');
                if (arr.Length >= 8)
                {
                    Entity.UserCardLogo logo = new Card.Entity.UserCardLogo();
                    logo.UserCardID = cardID;
                    logo.UserID = this.Passport.UserID;
                    logo.ImageType = faceType;
                    logo.Logo = arr[0];
                    logo.Width = decimal.Parse(arr[1]);
                    logo.Height = decimal.Parse(arr[2]);
                    logo.OriginalWidth = decimal.Parse(arr[3]);
                    logo.OriginalHeight = decimal.Parse(arr[4]);
                    logo.PosX = decimal.Parse(arr[5]);
                    logo.PosY = decimal.Parse(arr[6]);
                    logo.IsHidden = bool.Parse(arr[7]);
                    BLL.UserCardLogoManager.Add(logo, Passport);
                }
            }
        }
        /// <summary>
        /// 生成名片文件
        /// </summary>
        /// <param name="context"></param>
        /// <param name="cardID"></param>
        /// <returns></returns>
        private bool CreateMPFile(HttpContext context, int cardID)
        {
            string url = string.Format("{0}/ImageService.ashx?a=su&id={1}", Card.Utility.ImageUtilty.ImageServer, cardID);
            WebRequest request = HttpWebRequest.Create(url);
            request.Method = "GET";
            request.Headers.Add("Cookie", string.Format("{0}={1}", Card.CONST.CookieNames.Passport, CookieManager.GetCookie(Card.CONST.CookieNames.Passport)));

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            using (StreamReader dataStream = new StreamReader(response.GetResponseStream()))
            {
                var result = dataStream.ReadToEnd();
                JObject jResult = (JObject)JsonConvert.DeserializeObject(result);
                if (string.Compare(jResult.Property("r").Value.ToString(), CONST.YES_NO.YES, true) == 0)
                {
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region AddCart
        /// <summary>
        /// 向购物车添加名片
        /// </summary>
        /// <param name="context"></param>
        private void AddCart(HttpContext context)
        {
            string result = string.Empty;
            try
            {
                bool isAdjust = bool.Parse(context.Request.Form["adjust"]);
                string adjustDesc = isAdjust ? Utility.TextUtility.JSUnescape(context.Request.Form["adjustDesc"]) : string.Empty;
                string cardType = context.Request.Form["cardType"].Trim();
                int cardID = int.Parse(context.Request.Form["cardID"]);
                string paper = context.Request.Form["paper"].Trim();
                int num = int.Parse(context.Request.Form["num"]);
                string corner = context.Request.Form["corner"].Trim();

                Entity.CardSetting cardSetting = Common.SettingCache.GetCardSetting(paper);               
                Entity.CornerSetting cornerSetting = Common.SettingCache.GetCornerSetting(corner);
                Entity.CardPriceSetting priceSetting = Common.SettingCache.GetPriceSetting(cardSetting.CardCode.Trim(), num);

                int orderCardID = BAF.BLL.SYSSequenceManager.GetSequence(CONST.SEQUENCE_CODE.ORDER_CARD_ID, null);
                Entity.Cart cart = new Card.Entity.Cart();
                cart.UserID = this.Passport.UserID;
                cart.OrderCardID = orderCardID;
                cart.CardType = cardType;
                cart.BoxNum = num;
                cart.CardSettingCode = cardSetting.CardCode;
                cart.CardSettingName = cardSetting.CardName;
                cart.Price = priceSetting.Price;
                cart.CornerCode = cornerSetting.CornerCode;
                cart.CornerName = cornerSetting.CornerName;
                cart.CornerPrice = cornerSetting.Price;
                cart.IsAdjust = isAdjust;
                cart.AdjustDESC = isAdjust ? adjustDesc : string.Empty;
                cart.AdjustPrice = isAdjust ? 8 : 0;
                cart.TotalMoney = Math.Round(((cart.Price + cart.CornerPrice) * cart.BoxNum + cart.AdjustPrice), 2);

                bool isSucess = false;
                if (string.Compare(cardType, CONST.CARD_TYPE.USER_CARD, true) == 0)
                {
                    if (this.CreateOrderCardFiles(cardID, orderCardID))
                    {
                        isSucess = BLL.CartManager.AddCart(cart, cardID, orderCardID, this.Passport.UserID);
                    }
                }
                else
                {
                    isSucess = BLL.CartManager.AddCart(cart, cardID, orderCardID, this.Passport.UserID);
                }
                Common.CardWebUtility.SetCartInfo(this.Passport.UserID);
                result = isSucess ? "{'r':'y'}" : "{'r':'n','msg':'添加失败！'}";
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex.ToString());
                result = string.Format("{{'r':'n','msg':'{0}'}}", ex.Message);
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write(result);
        }

        private bool CreateOrderCardFiles(int cardID, int orderCardID)
        {
            string url = string.Format("{0}/ImageService.ashx?a=co&cid={1}&oid={2}&uid={3}", Card.Utility.ImageUtilty.ImageServer, cardID, orderCardID, this.Passport.UserID);
            WebRequest request = HttpWebRequest.Create(url);
            request.Method = "GET";
            request.Headers.Add("Cookie", string.Format("{0}={1}", Card.CONST.CookieNames.Passport, CookieManager.GetCookie(Card.CONST.CookieNames.Passport)));

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            using (StreamReader dataStream = new StreamReader(response.GetResponseStream()))
            {
                var result = dataStream.ReadToEnd();
                JObject jResult = (JObject)JsonConvert.DeserializeObject(result);
                if (string.Compare(jResult.Property("r").Value.ToString(), CONST.YES_NO.YES, true) == 0)
                {
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region 得到最新订单信息
        private void GetNewestOrder(HttpContext context)
        {
            StringBuilder sb = new StringBuilder("[");
            int recordCount = 20;
            if (context.Request.QueryString["r"] != null)
            {
                int.TryParse(context.Request.QueryString["r"], out recordCount);
            }

            DataTable dtItems = BLL.OrderItemManager.GetNewestItems(recordCount);
            if (dtItems != null && dtItems.Rows.Count > 0)
            {
                int rowCount = dtItems.Rows.Count;
                for (int i = 0; i < rowCount; i++)
                {
                    DataRow dr = dtItems.Rows[i];
                    //{ "uname": "aden20**", "tname": "彩色抽象型树叶个性名片", "desc": "直角|有微调|2盒", "time": "2013-02-13 13:55:20", "status": "制作中"}];
                    sb.Append("{'uname':'")
                      .Append(Card.Utility.TextUtility.JSEscape(DealUserName(dr["RECEIVER"].ToString().Replace('\'', ' '))))
                      .Append("','tname':'")
                      .Append(Card.Utility.TextUtility.JSEscape(dr["CARD_NAME"].ToString().Replace('\'', ' ')))
                      .Append("','desc':'")
                      .Append(Card.Utility.TextUtility.JSEscape(string.Format("{0}|{1}|{2}微调|{3}盒", dr["CORNER_NAME"].ToString(), dr["CARD_SETTING_NAME"].ToString(), dr["IS_ADJUST"].ToString() == "0" ? "无" : "有", dr["BOX_NUM"].ToString()).Replace('\'', ' ')))
                      .Append("','time':'")
                      .Append(DateTime.Parse(dr["CREATE_DATE"].ToString()).ToString("yyyy-MM-dd HH:mm:ss"))
                      .Append("','status':'")
                      .Append(CardWebUtility.GetOrderStatusDesc(dr["ORDER_STATUS_CODE"].ToString()));
                    if ((i + 1) == rowCount)
                    {
                        sb.Append("'}");
                    }
                    else
                    {
                        sb.Append("'},");
                    }

                }
            }
            sb.Append("]");
            context.Response.ContentType = "text/plain";
            context.Response.Write(sb.ToString());
        }

        private string DealUserName(string strName)
        {            
            char[] array = strName.Trim().ToCharArray();
            StringBuilder sb = new StringBuilder();
            int length = array.Length;
            int i=0;
            if (length > 2)
            {
                sb.Append(array[0]).Append(array[1]);
                i = 2;
            }
            else if (length == 2)
            {
                sb.Append(array[0]);
                i = 1;
            }

            for (; i < length; i++)
            {
                sb.Append("*");
            }

            return sb.ToString();

        }
        #endregion
    }
}
